#include<iostream>
#include<typeinfo>
#include<string>
#include<algorithm>
#include<utility>
#include<any>
#include<cassert>


using namespace std;

class Any
{
private:
      class hold
      {
      public:
            virtual ~hold(){}
            virtual const type_info& type()=0;
            virtual hold* clone()=0;
      };

      template<class T>
      class placehold:public hold
      {
      public:
            placehold(const T& val):val_(val){}
            //获取子类对象保存的类型
            virtual const type_info& type(){return typeid(T);}
            virtual hold* clone(){return new placehold(val_);}
      public:
            T val_;
      };
public:
      hold* content_;
public:
      Any():content_(nullptr){}
      template<class T>
      Any(const T& val):content_(new placehold<T>(val)){}
      Any(const Any& other)
      {
            content_=other.content_?other.content_->clone():nullptr;
      }
      ~Any(){delete content_;}
public:
      //返回子类对象保存数据的指针
      template<class T>
      T* get()
      {
            assert(typeid(T)==content_->type());
            return &(((placehold<T>*)content_)->val_);
      }
      //赋值运算符的函数重载
      template<class T>
      Any& operator=(const T& val)
      {
            Any tmp(val);
            swap(content_,tmp.content_);
            return *this;
      }
      Any& operator=(const Any& any)
      {
            Any tmp(any);
            swap(content_,tmp.content_);
            return *this;
      }
};

class Test
{
public:
      Test(){cout<<"构造"<<endl;}
      Test(const Test& t){cout<<"拷贝构造"<<endl;}
      ~Test(){cout<<"析构"<<endl;}
};

void test()
{
      Any a;
      a=10;
      int *p=a.get<int>();
      cout<<"*p:"<<*p<<endl;
      a=string("hello world");
      string* ps=a.get<string>();
      cout<<(*ps)<<endl;
       
}

void test1()
{
      any a;
      a=string("hello");
      string p=any_cast<string>(a);
      cout<<(p)<<endl;
}

void test2()
{
      std::any a;
      a = 10;
      int *pi = std::any_cast<int>(&a);
      std::cout << *pi << std::endl;

      a = std::string("hello");
      std::string *ps = std::any_cast<std::string>(&a);
      std::cout << *ps << std::endl;
}

int main()
{
      test1();
      return 0;
}


 